package myredis

import (
	"errors"
	"fmt"
	"strconv"
	"sync"

	"gopkg.in/redis.v5"

	"lottery/conf"
)

var mux sync.RWMutex
var cacheCli map[string]*redis.Client

func init() {
	cacheCli = make(map[string]*redis.Client)
}

func Open(name string) (cli *redis.Client, err error) {
	var ok bool
	mux.RLock()
	cli, ok = cacheCli[name]
	mux.RUnlock()
	if ok {
		return
	}

	res := conf.LoadResource()
	redisCfg, ok := res.Redis[name]
	if !ok {
		err = errors.New("配置不存在")
		return
	}

	addr := redisCfg.Host
	if redisCfg.Port > 0 {
		addr = fmt.Sprintf("%s:%d", addr, redisCfg.Port)
	}

	dbSelect, _ := strconv.Atoi(redisCfg.Db)
	cli = redis.NewClient(&redis.Options{
		Addr:     addr,
		Password: redisCfg.Passwd,
		DB:       dbSelect,
	})

	_, err = cli.Ping().Result()
	if err != nil {
		return
	}

	mux.Lock()
	cacheCli[name] = cli
	mux.Unlock()
	return
}

func OpenBase() (cli *redis.Client, err error) {
	return Open("base")
}
